package com.imageim.yimirror.ui.activity;

import android.graphics.Bitmap;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseActivity;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.ui.GlideUtils;
import com.imageim.yimirror.common.ui.btn.BtnCircleClose;
import com.imageim.yimirror.common.util.AppUtil;
import com.imageim.yimirror.common.util.CacheUtils;
import com.imageim.yimirror.common.util.ClickUtil;
import com.imageim.yimirror.common.util.PictureUtils;
import com.imageim.yimirror.common.util.UIUtils;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.ui.fragment.HistoryAnalysisFragment;
import com.imageim.yimirror.ui.fragment.MyCollectFragment;
import com.martin.ads.omoshiroilib.util.BitmapUtils;

import org.greenrobot.eventbus.EventBus;

import java.text.MessageFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Yuaihen.
 * on 2018/12/26
 */
public class PersonalCenterActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.iv_userHead)
    ImageView mIvUserHead;
    @BindView(R.id.btn_close)
    BtnCircleClose mBtnClose;
    @BindView(R.id.btn_history)
    Button mBtnHistory;
    @BindView(R.id.btn_my_like)
    Button mBtnMyLike;
    @BindView(R.id.fl_container)
    FrameLayout mFlContainer;
    @BindView(R.id.iv_qr_code)
    ImageView mIvQrCode;
    @BindView(R.id.tv_version)
    TextView mTvVersion;
    private FragmentTransaction mFragmentTransaction;
    private BaseFragment currentFragment;
    private HistoryAnalysisFragment mHistoryAnalysisFragment;
    private MyCollectFragment mCollectFragment;
    private FragmentManager mFragmentManager;

    @Override
    protected void initBundle() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_center;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mBtnClose.setCloseImage(R.drawable.ic_menu_exit, 300);
        mBtnClose.setOnTimeOverListener(new BtnCircleClose.OnTimeOverListener() {
            @Override
            public void onTimeOver() {
                EventBus.getDefault().post(new EventMessage(EventCode.CODE_FINISH, null));
                finish();
            }
        });
        mBtnClose.setOnCloseListener(new BtnCircleClose.OnCloseListener() {
            @Override
            public void onClose() {
                EventBus.getDefault().post(new EventMessage(EventCode.CODE_FINISH, null));
            }
        });
    }

    @Override
    protected void initData() {
        mTvVersion.setText(MessageFormat.format("形象力时尚AI {0}版", AppUtil.getVersionName(mContext)));
        if (!TextUtils.isEmpty(UserUtil.getQrCodeUrl())) {
            GlideUtils.display(mIvQrCode, UserUtil.getQrCodeUrl());
        }

        setUserHead();

        //默认加载智能分析Fragment
        setBtnSelect(HISTORY);
    }


    /**
     * 设置用户头像
     */
    private void setUserHead() {
        if (!TextUtils.isEmpty(CacheUtils.getString(mContext, Constants.FACE_STR))) {
            String faceStr = CacheUtils.getString(mContext, Constants.FACE_STR);
            Bitmap bitmap = BitmapUtils.base64ToBitmap(faceStr);
            if (bitmap != null) {
                Bitmap faceBitmap = PictureUtils.createCircleImage(bitmap, bitmap.getWidth());
                mIvUserHead.setImageBitmap(faceBitmap);
            }
        }
    }


    private static final int HISTORY = 0;
    private static final int MYLIKE = 1;

    /**
     * 设置按钮的选中
     *
     * @param index 选中按钮的位置
     */
    private void setBtnSelect(int index) {
        if (index == 0) {
            mBtnHistory.setSelected(true);
            mBtnHistory.setTextSize(UIUtils.dip2px(mContext, 36));
            mBtnMyLike.setSelected(false);
            mBtnMyLike.setTextSize(UIUtils.dip2px(mContext, 30));
            showAnalyzeFragment();
        } else {
            mBtnHistory.setSelected(false);
            mBtnHistory.setTextSize(UIUtils.dip2px(mContext, 30));
            mBtnMyLike.setSelected(true);
            mBtnMyLike.setTextSize(UIUtils.dip2px(mContext, 36));
            showCollectFragment();
        }
    }

    /**
     * 显示智能分析Fragment
     */
    private void showAnalyzeFragment() {
        if (currentFragment != null && currentFragment == mHistoryAnalysisFragment) {
            return;
        }

        if (mHistoryAnalysisFragment == null) {
            mHistoryAnalysisFragment = new HistoryAnalysisFragment();
        }
        addView(mHistoryAnalysisFragment, "mHistoryAnalysisFragment");
        currentFragment = mHistoryAnalysisFragment;
    }

    /**
     * 显示我的收藏Fragment
     */
    private void showCollectFragment() {
        if (currentFragment != null && currentFragment == mCollectFragment) {
            return;
        }

        if (mCollectFragment == null) {
            mCollectFragment = new MyCollectFragment();
        }
        addView(mCollectFragment, "mCollectFragment");
        currentFragment = mCollectFragment;
    }


    private void addView(BaseFragment fragment, String tag) {
        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        //优先检查，fragment是否存在，避免重叠
        BaseFragment tempFragment = (BaseFragment) mFragmentManager.findFragmentByTag(tag);
        if (tempFragment != null) {
            fragment = tempFragment;
        }
        if (fragment.isAdded()) {
            addOrShowFragment(fragment, tag);
        } else {
            if (currentFragment != null && currentFragment.isAdded()) {
                mFragmentTransaction.hide(currentFragment).add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
            } else {
                mFragmentTransaction.add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
            }
            currentFragment = fragment;
        }
    }


    /**
     * 添加或者显示 fragment
     *
     * @param fragment
     */
    private void addOrShowFragment(BaseFragment fragment, String tag) {
        if (currentFragment == fragment || mFragmentManager == null || currentFragment == null) {
            return;
        }
        // 如果当前fragment未被添加，则添加到Fragment管理器中
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (!fragment.isAdded()) {
            transaction.hide(currentFragment).add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
        } else {
            transaction.hide(currentFragment).show(fragment).commitAllowingStateLoss();
        }

        currentFragment.setUserVisibleHint(false);
        currentFragment = fragment;
        currentFragment.setUserVisibleHint(true);
    }


    @OnClick({R.id.btn_history, R.id.btn_my_like, R.id.iv_back})
    public void onViewClicked(View view) {
        if (ClickUtil.isValidClick()) {
            switch (view.getId()) {
                case R.id.btn_history:
                    setBtnSelect(HISTORY);
                    break;
                case R.id.btn_my_like:
                    setBtnSelect(MYLIKE);
                    break;
                case R.id.iv_back:
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

    private long lastTouchEventTime;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (System.currentTimeMillis() - lastTouchEventTime > 1000 && mBtnClose.getCount() < 60) {
            lastTouchEventTime = System.currentTimeMillis();
            mBtnClose.restart(300);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBtnClose != null) {
            mBtnClose.destory();
        }
    }
}
